﻿#region

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration.Json;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;

#endregion

namespace Vin.AspNetCore.Core.Extension;

public static class ConfigurationExtension
{
    /// <summary>
    /// 初始化配置文件
    /// </summary>
    /// <param name="builder"></param>
    public static void InitConfiguration(this WebApplicationBuilder builder)
    {
        
        if (!VinApp.VinInitBuilderConfig.PartialConfigDirPath.IsNullOrEmpty())
        {
            // 读取目录下的.json文件
            Directory.GetFiles(VinApp.VinInitBuilderConfig.PartialConfigDirPath!, "*.json").ToList()
                .ForEach(filePath =>
                {
                    builder.Configuration.Sources.Add(new JsonConfigurationSource()
                    {
                        Path = filePath,
                        Optional = true,
                        ReloadOnChange = true
                    });
                });
        }
        
        if (VinApp.VinInitBuilderConfig.PartialConfigFileNames.Count > 0)
        {
            VinApp.VinInitBuilderConfig.PartialConfigFileNames.ForEach(fileName =>
            {
                builder.Configuration.Sources.Add(new JsonConfigurationSource()
                {
                    Path = fileName,
                    Optional = true,
                    ReloadOnChange = true
                });
            });
        }
        
        VinApp.SetConfiguration(builder.Configuration);
    }
}